package com.fita.wechat.web.controller;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.utils.StringUtils;
import com.fita.entity.data.ShortUrl;
import com.fita.entity.data.Supplier;
import com.fita.entity.order.Order;
import com.fita.entity.order.OrderDetails;
import com.fita.entity.user.User;
import com.fita.wechat.Constant;
import com.fita.wechat.handler.SmsHandler;
import com.fita.wechat.service.DataService;
import com.fita.wechat.service.OrderService;
import com.fita.wechat.service.ShortUrlService;

/**
 * 
 * @author mohanlan
 *
 */
@RestController
@RequestMapping("/sms")
public class SmsController {

    private static final Logger logger = LoggerFactory.getLogger(SmsController.class);

    @Autowired
    private SmsHandler smsHandler;

    @Autowired
    @Qualifier("userService")
    private DataService<User> userService;
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private ShortUrlService shortUrlService;
    
    @Value("#{ctx['ctx.domain']}")
    private String systemHost;

    /**
     * 验证手机号是否已绑定用户
     * 
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/verify-mobile", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult verifyMobile(@RequestParam("mobile") String mobile) {

        HttpResult httpResult = new HttpResult();

        try {

            User user = userService.load(User.class, "mobile", mobile);

            if (user != null) {
                httpResult.fail("1").message("该手机号已绑定用户");
            } else {
                httpResult.success().message("该手机可用");
            }

        } catch (Exception e) {
            logger.error("#verifyMobile() - verify mobile failed, exception=[{}]", e);
            httpResult.fail("500").message("验证失败");
        }

        return httpResult;

    }

    /**
     * 
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/verify-code", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult sendVerifyCode(@RequestParam("mobile") String mobile) {

        HttpResult httpResult = new HttpResult();

        try {

            // Generate random code in 6 digits
            String code = smsHandler.generateVerifyCode(mobile);
            boolean send = smsHandler.sendVerifyCode(mobile, code);

            if (send) {

                String token = DigestUtils.sha256Hex(StringUtils.connect(mobile, code, Constant.SMS_CLIENT));
                httpResult.success().data("token", token).message("发送短信成功");
            } else {
                logger.error("#sendVerifyCode() faild with response [{}]", JsonUtils.toJson(httpResult));
                httpResult.fail("501").message("发送短信失败");
            }

        } catch (Exception e) {
            logger.error("#sendVerifyCode() occurs error", e);
            httpResult.fail("500").message("发送短信请求失败");
        }
        
        return httpResult;
    }
    
    /**
     * 
     * @param mobile
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/order-message", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult sendOrderMessage(@RequestParam("mobile") String mobile, @RequestParam("orderId") Long orderId) {

        HttpResult httpResult = new HttpResult();

        try {

            Order order = orderService.load(orderId);
            OrderDetails details = order.getDetails();
            ShortUrl pdf = shortUrlService.getByLongUrl(order.getPdfUrl());
            String pdfUrl = pdf != null ? pdf.getShortUrl() : null;
            ShortUrl system = shortUrlService.getByLongUrl(systemHost + "/orders/" + order.getId());
            String systemUrl = system != null ? system.getShortUrl() : null;
            boolean send = smsHandler.sendOrderMessage(mobile, details.getCustomerInfo().getSurname(), details.getCustomerInfo().getName(), order.getAlamoCode(), pdfUrl, systemUrl);

            if (send) {

                httpResult.success().message("发送短信成功");
            } else {
                logger.error("#sendOrderMessage() faild with response [{}]", JsonUtils.toJson(httpResult));
                httpResult.fail("501").message("发送短信失败");
            }

        } catch (Exception e) {
            logger.error("#sendOrderMessage() occurs error", e);
            httpResult.fail("500").message("发送短信请求失败");
        }
        
        return httpResult;
    }
    
    /**
     * 
     * @param mobile
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/staying-order-message", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult sendOrderStayingMessage(@RequestParam("mobile") String mobile, @RequestParam("orderId") Long orderId) {

        HttpResult httpResult = new HttpResult();

        try {

            Order order = orderService.load(orderId);
            Supplier supplier = orderService.loadSupplier(order.getBrand());
            ShortUrl system = shortUrlService.getByLongUrl(systemHost + "/shopping/result?orderId=" + order.getId() + "&type=pay");
            String systemUrl = system != null ? system.getShortUrl() : null;
            boolean send = smsHandler.sendOrderStayingMessage(mobile, supplier.getChineseName(), order.getCode(), order.getPickupDate(), order.getReturnDate(), systemUrl);

            if (send) {

                httpResult.success().message("发送短信成功");
            } else {
                logger.error("#sendOrderStayingMessage() faild with response [{}]", JsonUtils.toJson(httpResult));
                httpResult.fail("501").message("发送短信失败");
            }

        } catch (Exception e) {
            logger.error("#sendOrderStayingMessage() occurs error", e);
            httpResult.fail("500").message("发送短信请求失败");
        }
        
        return httpResult;
    }
    
    /**
     * 
     * @param mobile
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/cancel-order-message", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult sendOrderCancelMessage(@RequestParam("mobile") String mobile, @RequestParam("orderId") Long orderId) {

        HttpResult httpResult = new HttpResult();

        try {

            Order order = orderService.load(orderId);
            ShortUrl system = shortUrlService.getByLongUrl(systemHost + "/cars/search");
            String systemUrl = system != null ? system.getShortUrl() : null;
            boolean send = smsHandler.sendOrderCancelMessage(mobile, order.getAlamoCode(), systemUrl);

            if (send) {

                httpResult.success().message("发送短信成功");
            } else {
                logger.error("#sendOrderCancelMessage() faild with response [{}]", JsonUtils.toJson(httpResult));
                httpResult.fail("501").message("发送短信失败");
            }

        } catch (Exception e) {
            logger.error("#sendOrderCancelMessage() occurs error", e);
            httpResult.fail("500").message("发送短信请求失败");
        }
        
        return httpResult;
    }

}
